package com.penjin.android.activity.geren;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentActivity;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.loopj.android.http.RequestParams;
import com.loopj.android.http.TextHttpResponseHandler;
import com.penjin.android.R;
import com.penjin.android.constants.HttpConstants;
import com.penjin.android.domain.PenjinUser;
import com.penjin.android.http.HttpService;
import com.penjin.android.message.view.EaseSwitchButton;
import com.penjin.android.service.UserService;
import com.penjin.android.utils.HttpUtil;
import com.penjin.android.utils.ToastHelper;
import com.penjin.android.view.CustomProgressDialog;
import com.penjin.android.view.TitleBarView;

import org.apache.http.Header;
import org.json.JSONException;
import org.json.JSONObject;

/**
 * Created by Administrator on 2016/4/18.
 */
public class ResetPasswordActivity extends FragmentActivity implements View.OnClickListener {
    PenjinUser currentUser;

    TextView phone;
    EditText password;
    EditText newPassword;
    EditText confirmPassword;
    EaseSwitchButton switch_btn;
    View next;

    HttpService httpService;
    TextHttpResponseHandler handler;

    CustomProgressDialog progressDialog;
    TitleBarView titleBarView;
    boolean showPassword = false;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_activity_resetpwd);
        initData();
        initView();
        initHttp();
    }

    private void initData() {
        PenjinUser user = UserService.getInstance(getApplicationContext()).getCurrentUser();
        if (user != null) {//复制个人信息
            currentUser = new PenjinUser();
            currentUser.setUsername(user.getUsername());
            currentUser.setPhone(user.getPhone());
            currentUser.setCompanyId(user.getCompanyId());
            currentUser.setEmail(user.getEmail());
            currentUser.setSex(user.getSex());
            currentUser.setAddress(user.getAddress());
            currentUser.setRegion(user.getRegion());
            currentUser.setQianming(user.getQianming());
            currentUser.setTouxiang(user.getTouxiang());
            currentUser.setPassword(user.getPassword());
            currentUser.setChatId(user.getChatId());
            currentUser.setCompanyName(user.getCompanyName());
            currentUser.setStaffNum(user.getStaffNum());
            currentUser.setChatId(user.getChatId());
            currentUser.setUserId(user.getUserId());
        }
    }

    private void initView() {
        phone= (TextView) findViewById(R.id.phone);
        phone.setText(currentUser.getPhone());
        progressDialog = CustomProgressDialog.createDialog(this);
        progressDialog.setMessage("请稍后...");
        titleBarView = (TitleBarView) findViewById(R.id.titleBarView);
        titleBarView.setTitleBarListener(new TitleBarView.TitleBarListener() {
            @Override
            public void left(View view) {
                finish();
            }

            @Override
            public void center(View view) {

            }

            @Override
            public void right(View view) {

            }
        });
        password = (EditText) findViewById(R.id.password);
        newPassword = (EditText) findViewById(R.id.newPassword);
        confirmPassword = (EditText) findViewById(R.id.confirmPassword);
        next = findViewById(R.id.next);
        next.setOnClickListener(this);
        switch_btn = (EaseSwitchButton) findViewById(R.id.switch_btn);
        switch_btn.setOnClickListener(this);

    }

    private void initHttp() {
        httpService = HttpService.getInstance(this.getApplicationContext());
        handler = new TextHttpResponseHandler() {
            @Override
            public void onFailure(int i, Header[] headers, String s, Throwable throwable) {
                progressDialog.dismiss();
                if (s != null) {
                    System.out.println(s);
                }
            }

            @Override
            public void onSuccess(int i, Header[] headers, String s) {
                progressDialog.dismiss();
                try {
                    JSONObject jsonObject = new JSONObject(s);
                    boolean result = jsonObject.getBoolean("result");
                    if (result) {
                        ToastHelper.showMessage("修改密码成功", getApplicationContext());
                        UserService.getInstance(getApplicationContext()).saveUser(currentUser);
                        finish();
                    } else {
                        ToastHelper.showMessage("修改密码失败", getApplicationContext());
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        };

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.next:
                if (HttpUtil.isNetworkAvailable(this)) {
                    String pwd = newPassword.getEditableText().toString();
                    String confirmPwd = confirmPassword.getEditableText().toString();
                    int result = checkPassword(pwd, confirmPwd);
                    if (result != 0) {
                        return;
                    } else {
                        currentUser.setPassword(confirmPassword.getEditableText().toString());
                        progressDialog.show();
                        launchRequest();
                    }
                } else {
                    ToastHelper.showNoNetwork(this);
                }
                break;
            case R.id.switch_btn:
                showPassword(this.showPassword);
                if (this.showPassword == true) {
                    this.switch_btn.openSwitch();
                    this.showPassword = false;
                } else {
                    this.switch_btn.closeSwitch();
                    this.showPassword = true;
                }
                break;
        }
    }

    private void launchRequest() {
        RequestParams requestParams = new RequestParams();
        requestParams.put("username", currentUser.getPhone());
        requestParams.put("password", currentUser.getPassword());
        try {
            httpService.postRequest(this, HttpConstants.HOST + HttpConstants.AppResetPassword, requestParams, handler);
        } catch (Exception e) {
            e.printStackTrace();
            progressDialog.dismiss();
            ToastHelper.showMessage("网路请求出错，请重试", getApplicationContext());
        }
    }

    private int checkPassword(String pwd, String confirmPwd) {
        if (pwd == null || pwd.equals("")) {
            Toast.makeText(this, "密码不能为空", Toast.LENGTH_SHORT).show();
            return 1;
        }
        if (pwd.length() < 6) {
            Toast.makeText(this, "密码长度至少为6位", Toast.LENGTH_SHORT).show();
            return 2;
        }

        if (!pwd.equals(confirmPwd)) {
            Toast.makeText(this, "两次密码输入不一致", Toast.LENGTH_SHORT).show();
            return 3;
        }
        return 0;
    }

    private void showPassword(boolean show) {
        if (show) {
            this.newPassword.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
            this.confirmPassword.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
        } else {
            this.newPassword.setTransformationMethod(PasswordTransformationMethod.getInstance());
            this.confirmPassword.setTransformationMethod(PasswordTransformationMethod.getInstance());
        }

    }
}
